package com.yjzx.util.service.aop.ref.obj;

import com.yjzx.util.service.aop.ref.obj.enums.OperateEnum;
import com.yjzx.util.service.aop.ref.obj.event.CacheEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.function.Function;

/**
 * @author guozhi
 * @date 2024/10/30
 * @description 事件生产者(单体项目缓存)
 */
@Component
public class EventPublishService {
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 发布缓存处理事件
     * @param cacheName 缓存事件，如指定缓存没有存储的BaseCache，则该事件会被丢弃
     * @param data 数据
     * @param keyNameFunction 缓存key
     * @param operate 缓存处理方式
     * @param <T> 缓存数据类型
     * @param <V> 当前操作需要的类型
     */
    public <T,V>void publishList(String cacheName, List<V> data, Function<V, Object> keyNameFunction, OperateEnum operate) {
        applicationEventPublisher.publishEvent(new CacheEvent<V>(this, data, keyNameFunction, operate) {
            @Override
            public boolean supports(String cache) {
                return Objects.equals(cacheName, cache);
            }
        });
    }
    public <T,V>void publish(String cacheName, V data, Function<V, Object> keyNameFunction, OperateEnum operate) {
        applicationEventPublisher.publishEvent(new CacheEvent<V>(this, data, keyNameFunction, operate) {
            @Override
            public boolean supports(String cache) {
                return Objects.equals(cacheName, cache);
            }
        });
    }

}
